<?php

/**
 * FreeY_Db_Table
 *
 * @auther		FreeYadmin FreeYadmin@gmail.com
 * @update		FreeYadmin 
 * @package		FreeY 
 */	
class FreeY_Db_Driver_Mysql extends FreeY_Db_Driver_Abstract
{
	/**
	 * __construct
	 *
	 * @param $var
	 * @return viod
	 */
	public function __construct($db)
	{
		$this->_connect($db['host'], $db['user'], $db['password']);
		$this->_select_db($db['db_name']);
	}
	/**
	 * query 
	 *
	 * @param $var
	 * @return viod
	 */
	public function query($sql)
	{
		$this->_addLog($sql);
		$ret = @ mysql_query($sql, $this->link_id);
		$error = mysql_error();
		if ($error) {
			echo "\n<br>\n";
			echo "sql: " . $sql;
			echo "\n<br>\n";
			exit('query error: ' . $error);
		}

		return $ret;
	}
	/**
	 * result
	 *
	 * @param $sql string
	 * @param $type string
	 * @return mixed
	 */
	public function result($sql, $type = 'assoc')
	{
		$types = array('array', 'assoc', 'object');
		if(!in_array($type, $types))
		{
			$this->_addLog('result type error! type=' . $type);
			return ;
		}
		$resource = $this->query($sql);
		if(!$resource)
		{
			$this->_addLog('resource is null. line :' . __LINE__);
			return ;
		}
		$_mothed = '_fetch_' . $type;

		return $this->$_mothed($resource);
	}
	/**
	 * count
	 *
	 * @param $var
	 * @return viod
	 */
	public function count($sql)
	{
		$resource = $this->query($sql);
		if(!$resource)
		{
			$this->_addLog('resource is null. line :' . __LINE__);
			return ;
		}

		return $this->_num_rows($resource);
	}
	/**
	 * connect database server
	 *
	 * @param 
	 * @return viod
	 */
	protected function _connect($h, $u, $p)
	{
		if($this->pconnect)
			$this->link_id = mysql_pconnect($h, $u, $p);
		else
			$this->link_id = mysql_connect($h, $u, $p);
		if(!$this->link_id)
			$this->_addLog('connect database error. line :' . __LINE__);

		return ;
	}
	/**
	 * select database
	 *
	 * @param $db_name
	 * @return viod
	 */
	protected function _select_db($db_name)
	{
		mysql_select_db($db_name, $this->link_id);
	}
	/**
	 * fetch_array
	 *
	 * @param $resource
	 * @return array
	 */
	protected function _fetch_array($resource)
	{
		while($row=mysql_fetch_array($resource))
			$res[]=$row;

		return $res;
	}
	/**
	 * fetch_assoc
	 *
	 * @param $resource
	 * @return assoc array
	 */
	protected function _fetch_assoc($resource)
	{
		while($row=mysql_fetch_assoc($resource))
			$res[]=$row;

		return $res;
	}
	/**
	 * fetch_object
	 *
	 * @param $resource
	 * @return object
	 */
	protected function _fetch_object($resource)
	{
		while($row=mysql_fetch_object($resource))
			$res[]=$row;

		return $res;
	}
	/**
	 * _row_num
	 *
	 * @param $var
	 * @return viod
	 */
	protected function _num_rows($resource)
	{
		return mysql_num_rows($resource);
	}
}
//file end--------------------------------------------------------->